/**
 * 视频播放模块
 */
layui.define(['jquery','laytpl','layer'], function(exports) {

    var $ = layui.jquery,
    layer = layui.layer,
    laytpl = layui.laytpl;

    var xyvideo = {
        initVideo: function() {
            var that = this
            videojs('video_xiyu', {
                autoplay: false, // 自动播放
                muted: false,
                controls : false,// 是否显示控制栏
                // loop: true,
                poster : '/Public/common/img/course-default.png',
                preload: 'auto',
                // playbackRates :[0.5, 1, 1.5, 2],
                // 更多配置.....
            }, function() {
                videojs.log('播放器已经准备好了!');
                

                //加载右上角title
                that.createTitleEle(this);

                //加载控制条,绑定相应方法
                that.controlBar(this);

                $(document).off();//移除所有on绑定的方法
                that.initPlayOrPouse(this);//绑定开始或暂停
                that.initRate(this);//绑定倍数
                that.initVolume(this);//绑定音量
                that.initProgress(this);//绑定进度条
                that.enterScreenFull();//绑定全屏
                that.exitScreenFull();//退出全屏
            });
        },
        controlBar:function(player){
            var that = this;
            player.on('loadedmetadata',function(){
                var videoLength = player.duration();
                $(".video-duration > .full > span").html(that.time(videoLength));
                that.cacheLine(player);
                that.progressLine(player);
            });

            player.on("ended", function() {
                if($(".video-startorpause").find("i").hasClass("layui-icon-pause")){
                    $(".video-startorpause").find("i").removeClass("layui-icon-pause").addClass("layui-icon-play");
                }
                $(".video-duration > .currenttime").html(that.time(0));
                player.currentTime(0);
            });

            player.on('firstplay',function(){
                // Record(qid);
            })

            player.on('timeupdate',function(){
                var currentTime = player.currentTime().toFixed(0);
                $(".video-duration > .currenttime").html(that.time(currentTime));
                that.cacheLine(player);
                that.progressLine(player);
            });

            player.on('click',function(){
                if($(".video-startorpause").find("i").hasClass("layui-icon-play")){
                    $(".layui-icon-play").trigger("click");
                }else if($(".video-startorpause").find("i").hasClass("layui-icon-pause")){
                    $(".layui-icon-pause").trigger("click");
                }
            })

           
            
            
          
        },
        initPlayOrPouse:function(player){
            $(document).on('click','.layui-icon-play',function(){
                $(this).removeClass("layui-icon-play").addClass("layui-icon-pause");
                player.play();
                
            })
            
            $(document).on('click','.layui-icon-pause',function(){
                $(this).removeClass("layui-icon-pause").addClass("layui-icon-play");
                player.pause();
            })
        },
        initProgress:function(player){
            $(document).on('mousedown','.video-progress',function(e){
                var offsetX = e.pageX - $(".video-progress").offset().left;
                var percent = offsetX / $(".video-progress")[0].offsetWidth;
                $(".progressLine").css("width",(percent * 100).toFixed(1) + "%");
                player.currentTime(percent * player.duration());
                if(player.paused || player.ended){
                    $(".layui-icon-play").trigger('click');
                }
            })
        },
        initRate:function(player){
            
            $(document).on('click','.rate-list li',function(){
                if($(this).hasClass("on")){
                    return;
                }else{
                    var text = $(this).html();
                    $(this).parent().parent().parent().find("span").text(text);
                    $(this).addClass("on").siblings().removeClass("on");
                    // $(this).parent().parent().css("display","none");
                    player.playbackRate($(this).data("rate"));
                }
            })
        },
        initVolume:function(player){
            var that = this;
            $(document).on('click','.slider-box',function(e){
                var sliderTop = $(this).offset().top;
                var offset = e.pageY - sliderTop;
                if(offset>85) offset = 85;
                console.log(offset);
                that.setVolume(player,offset);
                $("#xyVideo").attr("data-vol-offset",offset);
            })

            //音量同步
            that.setVolume(player,$("#xyVideo").attr("data-vol-offset"));

        },
        setVolume:function(player,offset){
            var ty = -85 + offset;
            var per = offset / 85;
            per = per.toFixed(2);
            var v = 100 - parseInt(per*100);
            $(".volume-slider-anchor").css("transform","translate(0px, "+ty+"px)");
            $(".sc-cvidvg").css("height",v+'%');
            $(".slider>.value").text(v)
            player.volume(v/100);
        },
        createTitleEle:function(player){
            // 创建一个div节点
            var _html = '<div class="xiyu-text"><a href="">溪语编程</a></div>';
            var title = document.createElement('div');
            title.className = 'vjs-xiyucontrol-text';
            title.innerHTML = _html;
            // 添加进去，css设置好样式就可以了
            player.el().appendChild(title);
        },
        cacheLine:function(player){//缓存进度条
            var cachepercent = player.bufferedPercent();
            $(".cacheLine").css("width",(cachepercent * 100).toFixed(1) + "%");
        },
        progressLine:function(player){//播放进度条
            var progresspercent = player.currentTime() / player.duration();
            $(".progressLine").css("width",(progresspercent * 100).toFixed(1) + "%");
        },
        enterScreenFull:function(){
            $(document).on('click','.layui-icon-screen-full',function(){
                $(this).removeClass("layui-icon-screen-full").addClass("layui-icon-screen-restore");
                var full = document.getElementById("xyVideo");
                launchIntoFullscreen(full);
                $(".xiyu-video-control").addClass("full");
            })
        },
        exitScreenFull:function(){
            $(document).on('click','.layui-icon-screen-restore',function(){
                $(this).removeClass("layui-icon-screen-restore").addClass("layui-icon-screen-full");
                exitFullscreen();
                $(".xiyu-video-control").removeClass("full");
            })
            window.onresize = function() {
                var isFull = document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement ||document.webkitFullscreenElement || false;
                if (!isFull) {
                    //要执行的动作
                    $('.layui-icon-screen-restore').removeClass("layui-icon-screen-restore").addClass("layui-icon-screen-full");
                    $(".xiyu-video-control").removeClass("full");
                }
            }
        },
        time:function(value){
            let theTime = value;//秒
            let middle = 0;//分
            let hour = 0;//小时
            if (theTime > 59){
                middle = parseInt(theTime / 60);
                theTime = parseInt(theTime % 60);
            }
            if (middle > 59) {
                hour = parseInt(middle / 60);
                middle = parseInt(middle % 60);
            }
            theTime < 10 ? theTime = '0' + theTime : theTime = theTime
            middle < 10 ? middle = '0' + middle : middle = middle
            hour < 10 ? hour = '0' + hour : hour = hour
            return hour + ':' + middle + ':' + theTime
        },
        initData:function(id){
            var ii = layer.msg('Loading...', {
                icon: 16,
                time: 100000
            });
            var that = this;
            $.post('/kecheng/api/get_content_by_mid', {
                mid: id
            }, function(ret) {
                layer.close(ii);
                if (ret.status) {
                    for (var i = 0; i < ret.data.length; i++) {
                        if (ret.data[i].type == 'video') {
                            that.dispose();
                            that.htmlTpl(ret.data[i]);
                            that.initVideo();
                            
                            break;
                        }
                    };
                } else {
                    layer.msg(ret.info);
                }
            });
        },
        getPlayer:function(){
            return  videojs('video_xiyu');
        },
        htmlTpl : function(data){
            var tpl = $('#videoTpl').html();
            laytpl(tpl).render(data, function(html) {
                $("#xyVideo").html(html);
            });
        },
        dispose:function(){
            var myPlayer = $("#video_xiyu").get(0);
            if (typeof(myPlayer) != "undefined") {
                var Player = videojs('video_xiyu');
                Player.dispose();
            }
        }
    };

   //全屏
   function launchIntoFullscreen(element) {
        if(element.requestFullscreen){
            element.requestFullscreen();
        }
        else if(element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        }
        else if(element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        }
        else if(element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }
    }
    //退出全屏
    function exitFullscreen() {
        if(document.exitFullscreen) {
            document.exitFullscreen();
        } else if(document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if(document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }

    exports('xyvideo', xyvideo); //对外接口
});